package cn.kdlc.demo.bind.activity;

import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import cn.kdlc.demo.bind.R;
import cn.kdlc.demo.bind.adapter.UserAdapter;
import cn.kdlc.demo.bind.databinding.MainBinding;
import cn.kdlc.demo.bind.model.User;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private MainBinding binding;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        handler = new Handler();
        User user = new User();
        user.name = "Hello,China!";
        binding.setUser(user);

        final List<User> users = new ArrayList<User>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.name = "name" + i;
            users.add(u);
        }
        UserAdapter adapter = new UserAdapter(users);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setAdapter(adapter);
        binding.refresher.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < users.size(); i++) {
                            User u = users.get(i);
                            u.setName("new name" + i);
                        }
                        binding.refresher.setRefreshing(false);
                    }
                }, 2000);
            }
        });
    }

    public void changeText(View v) {
        User user = binding.getUser();
        user.setName("Hello,World!");
        binding.username.setTextColor(Color.parseColor("#ff0000"));
    }
}
